import React, { Component } from 'react'
import Link from '../link'
import style from './style'
import IconFont from '../iconFont'
import Button from '../button'
import cx from 'classnames'
import DnD from '../dnd'
import util from '../../util'
import { Spinner } from '../'

const Tr = ({children, ...others}) => (
    <div data-role="table-tr" {...others} className={style.tr}>{ children }</div>
)

const Td = ({children, width=1}) => (
    <div style={{flex: width}} className={style.td}>{ children }</div>
)

const Th = ({children, width=1}) => (
    <div style={{flex: width}} className={style.th}>{ children }</div>
)

function ToolTip(props){
    if (props) {
        const isHr = window.location.hash.indexOf('/hr/') === 1;
        let link = {};
        link = {
            target: props.target || '_blank',
            // 判断是否为人事页面，不是则跳转到此人的okr页面
            href: isHr? `#/hr/team-memeber-edit/${props.userId}`: `#/okr/objective-targetAll?userId=${props.userId}`
        };
    if(props.title) {
        return (
            <a className={style["toolTip"]} onMouseOver={mouseOver} onMouseOut={mouserOut} {...link} >
                <span className={style["toolTip-content"]} >{props.title}</span>
                <div  onMouseOver={mouseParentOver} onMouseOut={mouserParentOut} style={{overflow: 'hidden',textOverflow:'ellipsis', whiteSpace:'nowrap',maxWidth:'80px'}}>{props.children}</div>
            </a>
        );
    }else{
        return (
            <a href={props.href} className={style["toolTip"]} {...link}>
                <div style={{overflow: 'hidden',textOverflow:'ellipsis', whiteSpace:'nowrap',maxWidth:'80px'}}>{props.children}</div>
            </a>
        );
    }
    }
}

function mouseOver(e){
   e.target.children[0].style.opacity = 1;
}

function mouserOut(e){
   e.target.children[0].style.opacity = 0;
}


function mouseParentOver(e){
    e.target.parentElement.children[0].style.opacity = 1;
}

function mouserParentOut(e){
    e.target.parentElement.children[0].style.opacity = 0;
}

@DnD({
    ignored: '[disabled]',
    enter: style.enter
})
class SortableList extends Component {

    state = {
        hoverMap: {}
    }

    mouseEnter(e, i) {
        e.currentTarget.classList.add(style.enter)
        this.setState({
            hoverMap: {
                [i]: true
            }
        })
    }

    mouseLeave(e, i) {
        e.currentTarget.classList.remove(style.enter)
        this.setState({
            hoverMap: {
                [i]: false
            }
        })
    }

    componentWillReceiveProps(props) {
        const { dragEnd, from, to } = props
        if (!this.props.dragEnd && dragEnd) {
            this.props.sortUpdate({
                ...this.props.data[from],
                from,
                to
            })
        }
    }

    renderItem(v, i) {
        const { map, config, sortable } = this.props
        const render = (k, j) => {
            let value = v[k]
            if (map) {
                let cb
                if (cb = map[k]) {
                    value = cb(v[k], v, !!this.state.hoverMap[i])
                }
            }

            let width
            if (config) {
                width = config[k]
            }
            return (
                <Td width={width} key={j}>{value}</Td>
            )
        }

        let attr = {}
        if (typeof sortable === 'function') {
            if (!sortable(v)) attr.disabled=true
        }

        return (
            <Tr draggable key={i} {...attr}>
                {
                    this.props.keys.map(render)
                }
            </Tr>
        )
    }
    render() {
        return (
            <div className={style.body + ` ${style.sortable}`}>
                { this.props.data.map(::this.renderItem) }
            </div>
        )
    }
}

export default
class Table extends Component {

    hoverMap = {}

    state = {
        hoverMap: {},
        values:[],
        keys: []
    }

    mouseEnter(e, i) {
        e.currentTarget.classList.add(style.enter)
        this.hoverMap = {
            [i]: true
        }
        /*
            this.setState({
                hoverMap: {
                    [i]: true
                }
            })
        */
        //util.bus.emit('table:mouseenter', i)
    }

    mouseLeave(e, i) {
        e.currentTarget.classList.remove(style.enter)
        this.hoverMap = {
            [i]: false
        }
        /*
            this.setState({
                hoverMap: {
                    [i]: false
                }
            })
        */
        util.bus.emit('table:mouseleave', i)
    }

    componentWillReceiveProps(props) {
        if (!util.isNull(this.props.pagin) && !util.isNull(props.pagin)) {
            if (this.props.pagin.pageNumber != props.pagin.pageNumber) {
                this.props.pagin.fetch()
            }
        }

        if (!util.isShallowEqual(props.model, this.props.model)) {
            this.setState({
                keys: Object.keys(props.model),
                values: Object.keys(props.model).map((v) => props.model[v])
            })
        }

    }

    constructor(props) {
        super(props)

        const { model } = this.props
        this.state = {
            keys: Object.keys(model),
            values: Object.keys(model).map((v) => model[v])
        }
    }

    renderTh = (v, i) => {
        const { config } = this.props
        let width
        if (config) {
            width = config[this.state.keys[i]]
        }
        return (
            <Th width={width} key={i}> { v }</Th>
        )
    }

    renderHead = () => {
        if (this.props.head === false) return null
        return (
            <div data-role="thead" className={style.head}>
                <Tr>
                    { this.state.values.map(this.renderTh) }
                </Tr>
            </div>
        )
    }

    renderTd = (v, i) => {
        const { map, config } = this.props
        const render = (k, j) => {
            let value = v[k]
            if (map) {
                let cb
                if (cb = map[k]) {
                    value = cb(v[k], v)
                }
            }

            let width
            if (config) {
                width = config[k]
            }
            return (
                <Td width={width} key={j}>{value}</Td>
            )
        }

        let attr = {}
        if (this.props.onTrClick) {
            attr.onClick = () => this.props.onTrClick(i)
        }

        return (
            <Tr
                key={i}
                {...attr}
            >
                {
                    this.state.keys.map(render)
                }
            </Tr>
        )
    }

    renderBody = () => {
        const { sortable, loading, data } = this.props
        if (sortable) {
            return (
                <SortableList
                    keys={this.state.keys}
                    {...this.props}/>
            )
        }
        return (
            <div className={style.body}>
                {
                    this.props.data.map(this.renderTd)
                }
            </div>
        )
    }

    renderFoot = () => {
        const { children } = this.props
        if (!children) return null
        return (
            <div className={style.foot}>
                { children }
            </div>
        )
    }

    renderPagin() {
        if (!this.props.pagin) return null
        const { pagin } = this.props
        const { pageSize, pageNumber, totalNumber, onChange } = pagin
        const pageLength = Math.ceil(totalNumber/pageSize)
        if (pageLength <= 1) return null
        return (
            <div className={style.pagin}>
                <Link label="首页" onClick={() => onChange(1)}/>
                <ul>
                    {
                        new Array(pageLength+1).join('0').split('')
                            .map((v, i) => {
                                return (
                                    <li key={i}>
                                        <Link
                                            onClick={() => onChange(i+1)}
                                            className={cx({
                                                [style.active]: pageNumber == i+1
                                            })}
                                            noHover={pageNumber == i+1}
                                            label={i+1}/>
                                    </li>
                                )
                            })
                    }
                </ul>
                <Link label="末页" onClick={() => onChange(pageLength)}/>
            </div>
        )
    }

    render() {
        if (this.props.data == null) return null
        if (!this.props.data.length) return (
            <div style={{ textAlign: 'center', width: '162px', margin: 'auto', marginTop : '100px'}}>
                <img style={{ width: '150px', height: '150px' }} src={`/${util.getImagePath()}/default/table.png`}/>
                <div style={{ marginTop: '20px', fontSize: '18px', color: '#999' }}>没找到相关数据</div>
            </div>
        )
        return (
            <div
                data-role="table"
                className={
                    cx({
                        [style.root]: true,
                        [this.props.className]: !!this.props.className,
                        [style.white]: this.props.white,
                    })
                }
            >
                {
                    this.renderHead()
                }
                {
                    this.renderBody()
                }
                {
                    this.renderFoot()
                }
                {
                    this.renderPagin()
                }
            </div>
        )
    }
}

export
const map = {
    fullName: (...args) => {
        let [ v, user, target ] = args

        let link = {};
        if (v && user) {
            const isHr = window.location.hash.indexOf('/hr/') === 1;
            link = {
                target: target || '_blank',
                // 判断是否为人事页面，不是则跳转到此人的okr页面
                href: isHr? `#/hr/team-memeber-edit/${user.userId}`: `#/okr/objective-targetAll?userId=${user.userId}`
            };
        }

        return (!v || !user)? (
            <div
                style={{
                    display: 'flex',
                    alignItems: 'center'
                }}
            >
                <IconFont value="avatar" style={{ border: '1px solid #b9cee6', backgroundColor: '#eaf2fb', color: '#b9cee6', overflow: 'hidden', borderRadius: '50%', fontSize: '28px', width: '38px', 'height': '38px' }}/>
                <span style={{ marginLeft: '15px' }}>已删除</span>
            </div>
        ):(
            <div
                onClick={e => util.stopPropagation(e) }
                style={{
                    display: 'flex',
                    alignItems: 'center'
                }}
            >
                <a style={{ textDecoration: 'none', color: '#0779c3' }} {...link}>
                    {
                        user.avatarUrl?
                            <i style={{ borderRadius: '50%', width: '38px', height: '38px', backgroundImage: `url(${user.avatarUrl})`,display: 'block', ...util.crop(user.avatarUrl, 38) }}/>
                            : <IconFont value="avatar" style={{ border: '1px solid #b9cee6', backgroundColor: '#eaf2fb', color: '#b9cee6', overflow: 'hidden', borderRadius: '50%', fontSize: '28px', width: '38px', 'height': '38px' }}/>
                    }
                </a>
           {/*     <a style={{ textDecoration: 'none', color: '#0779c3', maxWidth: '80px', overflow: 'hidden',textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} {...link} >
                    <span style={{ marginLeft: '15px' }}>{ v }</span>
                </a>*/}
                    <ToolTip  target={target} userId = {user.userId} title={user.emailAddress}>{ v }</ToolTip>
            </div>
        )
    }
}
